﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Projektarbete.Popup;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Projektarbete
{
    /// <summary>
    /// The inventory that comes up when you hit the inventory button
    /// </summary>
    class MerchantPopup : PopupBase
    {
        //SE INVENTORYPOPUP FÖR BESKRIVNINGAR OM DET INTE FINNS\\

        private enum Direction { Up, Down }; //För att det är enklare
        private enum Regions { PlayerInventory, MerchantInventory };

        private Texture2D background;
        private Texture2D iconWeight;
        private Texture2D iconSize;
        private Texture2D iconValue;
        private SpriteFont spriteFont;
        private SpriteFont spriteFontSmall;

        private Vector2 position; //Position av fönstret (vart bakrunden ritas ut)
        private Point mousePoint; //Musposition

        private Item[] inventoryContents;
        private Item[] merchantContents;
        private Item selectedItem;
        private int inventoryItemScroll;
        private int merchantItemScroll;
        private int inventoryMaxItemScroll;
        private int merchantMaxItemScroll;

        private Regions lastRegion; //Hade spelaren musen över sitt inventory eller över kistans sist? inventory = true, kista = false

        private string itemDescription; //Beskrivningen av vad man klickar på
        private string itemName;
        private string itemWeight;
        private string itemSize;
        private string itemValue;
        private string playerWeight; //Hur mycket som är i spelarens inventory
        private string playerSize;
        private string playerGold;

        private Rectangle scissorRectangle; //Om något har en lång beskrivning, klipp ut allt som är utanför
        private Rectangle inventoryItemRectangle;
        private Rectangle merchantItemRectangle;

        //Temporära variabler så att man inte skapar nya varje frame
        private Vector2 tempVector2;
        private Rectangle tempRectangle;
        private Point tempPoint;
        private int tempInt;

        //Vart saker ska ritas ut
        private Vector2 weightDrawPosition;
        private Vector2 sizeDrawPosition;
        private Vector2 goldDrawPosition;

        private Vector2 itemDescriptionDrawPosition;
        private Vector2 itemNameDrawPosition;

        public MerchantPopup()
        {
            background = Global.LoadTexture2D("HUD/merchantHUD");
            spriteFont = Global.LoadSpriteFont("Fonts/inventoryFont");
            spriteFontSmall = Global.LoadSpriteFont("Fonts/inventoryFontSmall");

            iconWeight = Global.LoadTexture2D("HUD/Inventory/iconWeight");
            iconSize = Global.LoadTexture2D("HUD/Inventory/iconSize");
            iconValue = Global.LoadTexture2D("HUD/Inventory/iconValue");

            inventoryItemRectangle = new Rectangle(55, 69, 345, 300); //CHANGE IF ITEM BOX IS CHANGED
            merchantItemRectangle = new Rectangle(402, 69, 340, 300);
            scissorRectangle = new Rectangle(58, 384, 684, 158); //CHANGE IF DESCRIPTION BOX IS CHANGED!

            position = new Vector2(40, 40);
            weightDrawPosition = new Vector2(126, 47);
            sizeDrawPosition = new Vector2(310, 47);
            goldDrawPosition = new Vector2(452, 46);

            itemDescriptionDrawPosition = new Vector2(59, 400);
            itemNameDrawPosition = new Vector2(59, 381);

            inventoryItemScroll = 0;
            merchantItemScroll = 0;
            inventoryMaxItemScroll = 0;
            merchantMaxItemScroll = 0;

            lastRegion = Regions.PlayerInventory;

            tempInt = 0;
            tempVector2 = Vector2.Zero;
            tempRectangle = Rectangle.Empty;
            tempPoint = Point.Zero;

            itemDescription = string.Empty;
            itemName = string.Empty;
            itemWeight = string.Empty;
            itemSize = string.Empty;
            itemValue = string.Empty;
            playerGold = string.Empty;

            selectedItem = new ItemPresets.EmptySlot();

            inventoryContents = new Item[0];
            merchantContents = new Item[0];
        }

        public override void Update()
        {
            mousePoint = Input.GetMousePosition();

            if (inventoryItemRectangle.Contains(mousePoint))
                lastRegion = Regions.PlayerInventory;
            else if (merchantItemRectangle.Contains(mousePoint))
                lastRegion = Regions.MerchantInventory;

            #region scrolling
            //TODO: CHANGE KEYCONFIG UP/DOWN/LEFT/RIGHT
            if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up))
                Scroll(Direction.Up);
            else if (Input.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down))
                Scroll(Direction.Down);

            if (Input.GetLastMouseWheelValueNormalized() != Input.GetMouseWheelValueNormalized())
            {
                if (Input.GetMouseWheelValueNormalized() > Input.GetLastMouseWheelValueNormalized())
                    Scroll(Direction.Up);
                else
                    Scroll(Direction.Down);
            }
            #endregion

            #region clicking
            #region leftclick
            if (Input.IsMouseOneDown())
            {
                if (inventoryItemRectangle.Contains(mousePoint))
                {
                    tempInt = ToInventoryTile(mousePoint.Y);

                    selectedItem = inventoryContents[tempInt + inventoryItemScroll];

                    itemDescription = Global.TrimString(spriteFont, 684, selectedItem.getDescription);
                    itemName = selectedItem.getName;
                    itemWeight = selectedItem.getWeight.ToString();
                    itemSize = selectedItem.getSize.ToString();
                    itemValue = selectedItem.getValue.ToString();
                }
                else if(merchantItemRectangle.Contains(mousePoint))
                {
                    tempInt = ToInventoryTile(mousePoint.Y);

                    selectedItem = merchantContents[tempInt + merchantItemScroll];

                    itemDescription = Global.TrimString(spriteFont, 684, selectedItem.getDescription);
                    itemName = selectedItem.getName;
                    itemWeight = selectedItem.getWeight.ToString();
                    itemSize = selectedItem.getSize.ToString();
                    itemValue = selectedItem.getValue.ToString();
                }
            }
            #endregion

            #region rightclick
            if (Input.IsNewMouseTwoPress())
            {
                tempInt = ToInventoryTile(mousePoint.Y);

                if (inventoryItemRectangle.Contains(mousePoint))
                {
                    if (tempInt + inventoryItemScroll < inventoryContents.Length)
                        PopupManager.SellItem(inventoryContents[tempInt + inventoryItemScroll]);

                    ClearSelectedItem();
                    UpdateContents();
                }

                if (merchantItemRectangle.Contains(mousePoint))
                {
                    if (tempInt + merchantItemScroll < merchantContents.Length)
                        PopupManager.BuyItem(merchantContents[tempInt + merchantItemScroll]);

                    ClearSelectedItem();
                    UpdateContents();
                }
            }
            #endregion
            #endregion
        }

        /// <summary>
        /// Converts where the user clicks to which item should be accessed in inventoryContents[x]
        /// </summary>
        /// <param name="y">Mouse y-position</param>
        /// <returns></returns>
        private int ToInventoryTile(int y)
        {
            return (int)Math.Floor((y - 70) / 30f); //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!
        }

        /// <summary>
        /// Updates the content to display
        /// </summary>
        public void UpdateContents()
        {
            #region kistan
            LinkedList<Item> tempMerchantContents = AIManager.getMerchant(Vector2.Multiply(Player.GetFacingPositionAsVector2(), 24)).inventory.contents;

            merchantContents = new Item[tempMerchantContents.Count];

            int index = 0;

            foreach (Item item in tempMerchantContents)
            {
                merchantContents[index] = item;
                index++;
            }

            merchantMaxItemScroll = merchantItemScroll + 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (merchantMaxItemScroll >= merchantContents.Length)
                merchantMaxItemScroll = merchantContents.Length;

            merchantItemScroll = merchantMaxItemScroll - 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (merchantItemScroll < 0)
                merchantItemScroll = 0;

            merchantItemRectangle.Height = merchantContents.Length * 30;

            if (merchantItemRectangle.Height > 300)
                merchantItemRectangle.Height = 300;
            #endregion

            #region spelaren
            inventoryContents = Player.inventory.GetContentsAsArray;

            inventoryMaxItemScroll = inventoryItemScroll + 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (inventoryMaxItemScroll >= inventoryContents.Length)
                inventoryMaxItemScroll = inventoryContents.Length;

            inventoryItemScroll = inventoryMaxItemScroll - 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

            if (inventoryItemScroll < 0)
                inventoryItemScroll = 0;

            playerWeight = Player.inventory.getCurrentWeight.ToString() + "/" + Player.inventory.getMaxWeight.ToString();
            playerSize = Player.inventory.getCurrentSize.ToString() + "/" + Player.inventory.getMaxSize.ToString();

            inventoryItemRectangle.Height = inventoryContents.Length * 30;

            if (inventoryItemRectangle.Height > 300)
                inventoryItemRectangle.Height = 300;

            playerGold = Player.gold.ToString();
            #endregion
        }

        /// <summary>
        /// Scrolls the items
        /// </summary>
        /// <param name="direction"></param>
        private void Scroll(Direction direction)
        {
            if (lastRegion == Regions.PlayerInventory)
            {
                if (direction == Direction.Up)
                {
                    inventoryItemScroll--;

                    UpdateItemScroll();
                }
                else if (direction == Direction.Down)
                {
                    inventoryItemScroll++;

                    UpdateItemScroll();
                }
            }
            else
            {
                if (direction == Direction.Up)
                {
                    merchantItemScroll--;

                    UpdateItemScroll();
                }
                else if (direction == Direction.Down)
                {
                    merchantItemScroll++;

                    UpdateItemScroll();
                }
            }
        }

        /// <summary>
        /// Clamps ItemScroll, updates MaxItemScroll and clamps it
        /// </summary>
        private void UpdateItemScroll()
        {
            if (lastRegion == Regions.PlayerInventory)
            {
                if (inventoryItemScroll < 0)
                    inventoryItemScroll = 0;

                //Se till så att itemScroll
                if (inventoryItemScroll >= inventoryContents.Length - 10) //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!
                    inventoryItemScroll = inventoryContents.Length - 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

                inventoryMaxItemScroll = inventoryItemScroll + 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

                if (inventoryMaxItemScroll >= inventoryContents.Length)
                    inventoryMaxItemScroll = inventoryContents.Length;

                if (inventoryItemScroll < 0)
                    inventoryItemScroll = 0;
            }
            else
            {
                if (merchantItemScroll < 0)
                    merchantItemScroll = 0;

                if (merchantItemScroll >= merchantContents.Length - 10) //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!
                    merchantItemScroll = merchantContents.Length - 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

                merchantMaxItemScroll = merchantItemScroll + 10; //CHANGE IF VALUE/WEIGHT/SIZE DRAW POSITION IS CHANGED!

                if (merchantMaxItemScroll >= merchantContents.Length)
                    merchantMaxItemScroll = merchantContents.Length;

                if (merchantItemScroll < 0)
                    merchantItemScroll = 0;
            }
        }

        /// <summary>
        /// Clears the selected item
        /// </summary>
        public void ClearSelectedItem()
        {
            selectedItem = new ItemPresets.EmptySlot();

            itemDescription = string.Empty;
            itemName = string.Empty;
            itemWeight = string.Empty;
            itemSize = string.Empty;
            itemValue = string.Empty;
        }

        /// <summary>
        /// Draws the entire popup
        /// </summary>
        /// <param name="spriteBatch">spritebatch</param>
        /// <param name="graphicsDevice">graphicsDevice</param>
        public override void Draw(SpriteBatch spriteBatch, GraphicsDevice graphicsDevice)
        {
            spriteBatch.Draw(background, position, Color.White);

            #region spelarens inventory
            for (int x = inventoryItemScroll; x < inventoryMaxItemScroll; x++)
            {
                //Bild
                tempVector2.X = 59;
                tempVector2.Y = 70 + (x - inventoryItemScroll) * 30;
                //TODO: COLORS?
                spriteBatch.Draw(inventoryContents[x].getTexture, tempVector2, Color.White); //Items bild

                //Text
                tempVector2.X = 80;
                tempVector2.Y = 65 + (x - inventoryItemScroll) * 30;

                spriteBatch.DrawString(spriteFont, inventoryContents[x].getName, tempVector2, Color.White); //Items namn

                //Bilder
                tempVector2.Y = 85 + (x - inventoryItemScroll) * 30;

                spriteBatch.Draw(iconValue, tempVector2, Color.White); //Rita ut ikonen för värde

                tempVector2.X = 150;

                spriteBatch.Draw(iconWeight, tempVector2, Color.White); //Rita ut ikonen för vikt

                tempVector2.X = 200;

                spriteBatch.Draw(iconSize, tempVector2, Color.White); //Rita ut ikonen för storlek

                tempVector2.X = 110;


                //Text
                tempVector2.Y = 81 + (x - inventoryItemScroll) * 30;

                tempVector2.X = 90;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getValue.ToString(), tempVector2, Color.White); //Guld

                tempVector2.X = 160;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getWeight.ToString(), tempVector2, Color.White); //Vikt

                tempVector2.X = 210;

                spriteBatch.DrawString(spriteFontSmall, inventoryContents[x].getSize.ToString(), tempVector2, Color.White); //Storlek
            }
            #endregion

            #region kistans prylar
            for (int x = merchantItemScroll; x < merchantMaxItemScroll; x++)
            {
                //Bild
                tempVector2.X = 404;
                tempVector2.Y = 70 + (x - merchantItemScroll) * 30;
                //TODO: COLORS?
                spriteBatch.Draw(merchantContents[x].getTexture, tempVector2, Color.White); //Items bild

                //Text
                tempVector2.X = 425;
                tempVector2.Y = 65 + (x - merchantItemScroll) * 30;

                spriteBatch.DrawString(spriteFont, merchantContents[x].getName, tempVector2, Color.White); //Items namn

                //Bilder
                tempVector2.Y = 85 + (x - merchantItemScroll) * 30;

                spriteBatch.Draw(iconValue, tempVector2, Color.White); //Rita ut ikonen för värde

                tempVector2.X = 495;

                spriteBatch.Draw(iconWeight, tempVector2, Color.White); //Rita ut ikonen för vikt

                tempVector2.X = 545;

                spriteBatch.Draw(iconSize, tempVector2, Color.White); //Rita ut ikonen för storlek

                tempVector2.X = 455;


                //Text
                tempVector2.Y = 81 + (x - merchantItemScroll) * 30;

                tempVector2.X = 435;

                spriteBatch.DrawString(spriteFontSmall, merchantContents[x].getValue.ToString(), tempVector2, Color.White); //Guld

                tempVector2.X = 505;

                spriteBatch.DrawString(spriteFontSmall, merchantContents[x].getWeight.ToString(), tempVector2, Color.White); //Vikt

                tempVector2.X = 555;

                spriteBatch.DrawString(spriteFontSmall, merchantContents[x].getSize.ToString(), tempVector2, Color.White); //Storlek
            }
            #endregion

            spriteBatch.DrawString(spriteFont, playerWeight, weightDrawPosition, Color.White); //Spelarens inventorys vikt + maxvikt
            spriteBatch.DrawString(spriteFont, playerSize, sizeDrawPosition, Color.White); //Spelarens inventorys storlek + maxstorlek
            spriteBatch.DrawString(spriteFont, playerGold, goldDrawPosition, Color.White); //Hur mycket guld spelaren har

            if (itemName != string.Empty) //Om spelaren har klickat på ett item
            {
                //Bilder
                tempVector2.X = 576;
                tempVector2.Y = 533;

                spriteBatch.Draw(iconValue, tempVector2, Color.White); //Rita ut ikonen för värde

                tempVector2.X = 646;

                spriteBatch.Draw(iconWeight, tempVector2, Color.White); //Rita ut ikonen för vikt

                tempVector2.X = 696;

                spriteBatch.Draw(iconSize, tempVector2, Color.White); //Rita ut ikonen för storlek

                //Text
                tempVector2.X = 585;
                tempVector2.Y = 529;

                spriteBatch.DrawString(spriteFontSmall, itemValue, tempVector2, Color.White); //Guld

                tempVector2.X = 655;

                spriteBatch.DrawString(spriteFontSmall, itemWeight, tempVector2, Color.White); //Vikt

                tempVector2.X = 705;

                spriteBatch.DrawString(spriteFontSmall, itemSize, tempVector2, Color.White); //Storlek

                spriteBatch.End();

                graphicsDevice.RasterizerState = new RasterizerState() { ScissorTestEnable = true };
                graphicsDevice.ScissorRectangle = scissorRectangle;

                spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, graphicsDevice.RasterizerState);

                spriteBatch.DrawString(spriteFont, itemName, itemNameDrawPosition, Color.White);
                spriteBatch.DrawString(spriteFont, itemDescription, itemDescriptionDrawPosition, Color.White);

                spriteBatch.End();

                //TODO: REMOVE ??
                spriteBatch.Begin();
            }
        }
    }
}